package com.project.git.homwork3_29;


import com.project.git.homwork3_29.BaseDao;

import java.lang.reflect.Field;
import java.sql.*;
import java.time.LocalDate;

/**
 * 所有Dao父类
 */
public class BaseDao {
    /**
     * 连接对象
     */
    protected Connection con;
    /**
     * SQL语句执行对象
     */
    protected PreparedStatement ps;
    /**
     * 结果集对象
     */
    protected ResultSet rs;

    /**
     * 加载连接
     */
    public void setConnection() {
        try {
            Class.forName("com.mysql.jdbc.Driver");
            this.con = DriverManager.getConnection("jdbc:mysql://localhost:12345/db?characterEncoding=utf-8",
                    "root", "lovo");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 关闭连接
     */
    public void closeConnection() {
        try {
            if (rs != null) {
                rs.close();
            }
            if (ps != null) {
                ps.close();
            }
            if (con != null) {
                con.close();
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }

      public void add(Object objectBean) {
          Column c1 = null;
          this.setConnection();
          Class c = objectBean.getClass();
          String sql ="insert into t_Student ( ";
          Field[] f = c.getDeclaredFields();
          Object[] values  = new Object[f.length-1];
          for (Field f1 : f) {
              if (f1.isAnnotationPresent(Column.class)) {
                  c1 = f1.getAnnotation(Column.class);
                  sql +=c1.value()+",";
              }
          }
          try {
              ps = con.prepareStatement(sql.substring(0,52)+")"+"values(?,?,?,?,?)");
              for(int i = 0;i<values.length;i++){
                 ps.setObject(i+1,values[i]);
              }
              ps.executeUpdate();
          } catch (SQLException throwables) {
              throwables.printStackTrace();
          }
          finally {
              this.closeConnection();
          }
      }


    public static void main(String[] args) {
        BaseDao b = new BaseDao();
        b.add(new StudentBean("张三","男","110",LocalDate.parse("2001-02-03"),"110@qq.com"));
    }
}

